﻿DECLARE @Var_Flag INT SET @Var_Flag = @Flag_In
DECLARE @Var_PatientId VARCHAR(100) SET @Var_PatientId = @PatientId_In
SELECT A.PatientId
      ,A.PatientName
      ,A.kscode AS DeptCode
      ,A.ksname AS DeptName
      ,CASE WHEN a.yscode is null or a.yscode='' THEN '*' ELSE a.yscode END AS DoctCode
      ,CASE WHEN a.ysname is null or a.ysname='' THEN '任意医师' ELSE a.ysname END AS DoctName
      ,A.XMCode
      ,A.XMName
      ,A.XMMoney
      ,A.MZNum
      ,A.CallNum
      --,B.Id AS HISTransNo
      --,B.FPNum AS InvoiceTransNo
      ,A.RegisterDate AS RegistDate
	  ,A.processdate AS ProcessDate
      ,CASE WHEN a.deldate is not null THEN -1 ELSE CASE WHEN a.processdate is not null THEN 1 ELSE 0 END END AS isTreat
      ,CAST(isnull(0,0) AS int) as IsCheckIn
      ,C.BegTime
      ,C.ENDTime
      ,ISNULL(ISNULL(C.Address,D.Address),E.KSAddress) AS Address
FROM MZRegisterSheet a(NOLOCK) 
--JOIN AP_OrderSheet b(NOLOCK) ON A.FPNum=B.FPNum
LEFT JOIN MZScheduleDetails C(NOLOCK) ON A.MZNum=C.MZNum
LEFT JOIN MZSchedule D(NOLOCK) ON A.KSCode=D.KSCode AND CASE WHEN A.YSCode IS NULL OR A.YSCode='' THEN '*' ELSE A.YSCode END=D.YSCode AND DATEPART(WEEKDAY,A.RegisterDate) = D.Weekday
LEFT JOIN KSCode E(NOLOCK) ON A.KSCode=E.Code
WHERE a.PatientID=@Var_PatientId AND
       a.DelDate IS NULL AND
       a.RegisterDate > GETDATE() -3 AND
	  (A.MZNum IN (SELECT MZNum FROM MZCFINF_YZ (NOLOCK) WHERE PatientId = @Var_PatientId AND CASE WHEN MZOPERDATE IS NULL THEN 1 ELSE 2 END | @Var_Flag = @Var_Flag) OR
	   A.MZNum IN (SELECT MZNum FROM PATIENT_APPLICATIONSHEET (NOLOCK) WHERE PatientId = @Var_PatientId AND CASE WHEN JZOPER IS NULL THEN 1 ELSE 2 END | @Var_Flag = @Var_Flag))